package com.ykzb.user.controller;

import com.ykzb.base.bean.ResultBean;
import com.ykzb.base.exception.BusinessException;
import com.ykzb.constants.Constants;
import com.ykzb.constants.UrlConstants;
import com.ykzb.enums.MsgEnumType;
import com.ykzb.enums.SSDBKeys;
import com.ykzb.redis.RedisClient;
import com.ykzb.user.service.UserService;
import com.ykzb.util.CryptUtil;
import com.ykzb.util.RSACoder;
import com.ykzb.util.RSAKey;
import com.ykzb.user.model.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
@RequestMapping("/user")
public class UserController {

	protected Log log = LogFactory.getLog(this.getClass().getName());

	@Autowired
	private RedisClient redisClient;


	@Autowired
	private UserService userService;

	/**
	 * 跳转到用户登录页
	 * @return
	 */
	@RequestMapping(value = UrlConstants.USER_TO_LOGIN,method={RequestMethod.GET, RequestMethod.POST})
	public ModelAndView toLogin()
	{
		return new ModelAndView("login");
	}

	/**
	 * 用户登录
	 * @return
	 */
	@RequestMapping(value = UrlConstants.USER_LOGIN,method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public ResultBean login(HttpServletRequest request,String userName,String password)
	{
		ResultBean ret = null;
		try {
			ret = userService.login(request,userName,password);
		} catch (Exception e) {
			log.error(userName+"登录不成功！");
			e.printStackTrace();
		}
		return ret;
	}

	/**
	 * 用户退出登录
	 * @return
	 */
	@RequestMapping(value = UrlConstants.USER_EXIT,method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public ResultBean userExit(HttpServletRequest request)
	{
		ResultBean ret = new ResultBean();
		try {
			if (request.getSession()!=null){
				request.getSession().invalidate();
			}
			ret.setSuccess(true);
		} catch (Exception e) {
			ret.setSuccess(false);
			log.error("登录退出异常！");
			e.printStackTrace();
		}
		return ret;
	}


	/**
	 * 用户手机号注册
	 * @param code
	 * @param user
	 * @return
	 */
	@RequestMapping(value = UrlConstants.USER_REGISTER,method ={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public ResultBean register(HttpServletRequest request, String code, User user) throws  Exception{
		ResultBean ret = new ResultBean();
		if (StringUtils.isNotBlank(code) && StringUtils.isNotEmpty(user.getPwd()) && StringUtils.isNumeric(user.getMobile())) {

				// 校验验证码
				String correctCode = redisClient.getJedis().get(SSDBKeys.mobile_code + user.getMobile());
				if (!code.equals(correctCode)) {
					ret.setSuccess(false);
					log.warn("resgister mobile:{} input error regCode:{}, correctCode:{}"+user.getMobile()+":"+code+":"+correctCode);
					throw new BusinessException(MsgEnumType.INVALID_REGISTER_CODE);
				}

				// 校验手机号
				boolean mobileExists = userService.isMobileExists(user.getMobile());
				if (mobileExists) {
					ret.setSuccess(false);
					throw new BusinessException(MsgEnumType.REPEAT_REGISTER_MOBILE);
				}
			    //模拟APP加密
				String pass = RSACoder.encryptByPublicKey2Base64(RSAKey.REGISTER_PUBLIC_KEY, user.getPwd());
				//解密
			    String pass2 = RSACoder.decryptByPrivateKey4Base64(RSAKey.REGISTER_PRIVATE_KEY, pass);
				user.setPwd(pass2);
				user.setAvatarKey("");
			    user.setAvatarKeyVersion(0);
			    user.setSex(1);
				user.setRegisterType(1);
				user.setCreateTime(new Date());
				user.setModifyTime(new Date());
				user.setIsTalent(0);
				try{
					userService.insert(user);
					ret.setSuccess(true);
				}catch (Exception e){
					e.printStackTrace();
					log.error(e);
					ret.setSuccess(false);
				}
				//把用户追加到session中
				request.getSession().setAttribute(Constants.USER_SESSIOON_NAME,user);
		}else{
			log.info("登录的手机号密码或验证码为空");
			ret.setSuccess(false);
		}
		return ret;
	}

	/**
	 * 获取注册码
	 * @return
	 */
	@RequestMapping(value = UrlConstants.USER_GET_REGISTER_CODE,method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public ResultBean getRegisterCode(String mobile) throws Exception{
		try{
			return userService.getRegisterCode(mobile);
		}catch (Exception e){
			log.error("获取注册码出错：", e);
			return null;
		}
	}

	/**
	 * 跳转到注册到注册页
	 * @return
	 */
	@RequestMapping(value = UrlConstants.USER_TO_REGISTER,method={RequestMethod.GET, RequestMethod.POST})
	public ModelAndView toRegister()
	{
		return new ModelAndView("registerSelect");
	}


	/**
	 * 跳转到注册到客户注册页
	 * @return
	 */
	@RequestMapping(value = UrlConstants.USER_TO_REGISTER_CUSTOMER,method={RequestMethod.GET, RequestMethod.POST})
	public ModelAndView toRegisterCustomer()
	{
		return new ModelAndView("registerCustomer");
	}

	/**
	 * 跳转到注册到GEEK注册页
	 * @return
	 */
	@RequestMapping(value = UrlConstants.USER_TO_REGISTER_GEEK,method={RequestMethod.GET, RequestMethod.POST})
	public ModelAndView toRegisterClientGeek()
	{
		return new ModelAndView("registerGeek");
	}


	public static void main(String[] args) {
		String password = "1234";
		try {
			String code = CryptUtil.md5(password).toLowerCase();
			System.out.print("***************************"+code);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
